#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_COLS 20
#define MAX_INPUT 1000

int read_column_numbers(int columns[], int max);

int rearrange(char *output, char const *input, int n_columns, int const columns[]);

int main() {
    int n_columns;
    int columns[MAX_COLS];
    char input[MAX_INPUT];
    char output[MAX_INPUT];

    n_columns = read_column_numbers(columns, MAX_COLS);

    printf("start gets");
    while (gets(input) != NULL) {
        printf("origin input: $s\n", input);
        rearrange(output, input, n_columns, columns);
        printf("rearrange line: %s\n", output);
    }


}

/**
 * 读取列号，超出的部分不予理会
 */
int read_column_numbers(int columns[], int max) {
    int num = 0;
    int ch;
    printf("input columns\n");
    while (num < max && scanf("%d", &columns[num]) == 1 && columns[num] >= 0) {
        num += 1;
    }
    printf("end input columns\n");
    /**
     * 确认读取到了偶数个参数
     */
    if (num % 2 != 0) {
        puts("last column number is not paired!!");
        exit(EXIT_FAILURE);
    }
    return num;
}

/**
 *
 * @param output
 * @param input
 * @param n_columns
 * @param columns
 * @return
 * 处理行输入
 */
int rearrange(char *output, char const *input,
              int n_columns, int const columns[]) {
    int col;
    int output_col;
    int len;

    len = strlen(input);
    output_col = 0;

    /**
     * c处理每队标号
     */
    for (col = 0; col < n_columns; col += 2) {
        int nchars = columns[col + 1] - columns[col] + 1;
        if (columns[col] >= len || output_col == MAX_INPUT - 1) {
            break;
        }
        strncpy(output + output_col, input + columns[col], nchars);
        output_col += nchars;
        output[output_col] = '\0';
    }
}

